<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>账号登录</h2>
        <p>欢迎回到在线学习平台</p>
      </div>
      
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          />
        </el-form-item>
        
        <div class="login-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <router-link to="/reset-password" class="forgot-password">
            忘记密码?
          </router-link>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-button" 
            :loading="loading" 
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-link">
        还没有账号? 
        <router-link to="/register">立即注册</router-link>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'LoginPage',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const formRef = ref(null)
    const loading = computed(() => store.state.isLoading)
    
    const formData = reactive({
      username: '',
      password: ''
    })
    
    const rememberMe = ref(false)
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ]
    }
    
    const handleLogin = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate(async (valid) => {
          if (valid) {
            const result = await store.dispatch('login', formData)
            
            if (result.success) {
              ElMessage.success('登录成功')
              
              // 登录成功后立即获取最新的用户信息，确保头像等数据是最新的
              await store.dispatch('fetchUserInfo')
              
              // 如果有重定向路径，跳转到该路径
              const redirectPath = route.query.redirect || '/'
              router.push(redirectPath)
            } else {
              ElMessage.error(result.message || '登录失败')
            }
          }
        })
      } catch (error) {
        ElMessage.error('登录异常，请稍后重试')
      }
    }
    
    onMounted(() => {
      // 检查是否已经登录
      if (store.getters.isAuthenticated) {
        router.push('/')
      }
    })
    
    return {
      formRef,
      loginForm: formData,
      rules,
      rememberMe,
      loading,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 140px);
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 10px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 14px;
  color: #909399;
}

.login-button {
  width: 100%;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-password {
  font-size: 14px;
  color: #409EFF;
  text-decoration: none;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.register-link a {
  color: #409EFF;
  text-decoration: none;
}
</style> 